import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Select, InputNumber, message, Input } from 'antd'
import _ from 'loadsh'
import { Line, Cell, Split } from '@components/ApprovePre/Approve'
import style from './SecretaryInput.module.less'
import Dictionary from '@js/dictionary'

const { Item } = Form
const { Option, OptGroup } = Select
const layout = { labelCol: { flex: '80px' } }
class SecretaryInput extends Component {
  state = {
    keyTitleMap: {},
    partyIdNameMap: {},
    courtList: [],
    filterCourts: [],
    sealTypes: []
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.instance || {}, 'currentStep.vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  initPartyIdNameMap () {
    const caseDetail = this.props.caseDetail || {}
    const applicants = _.get(caseDetail, 'applicants', [])
    const respondents = _.get(caseDetail, 'respondents', [])
    const map = {}
    applicants.filter(li => li.status).forEach(li => { map[li.id] = li.name })
    respondents.filter(li => li.status).forEach(li => { map[li.id] = li.name })
    this.setState({ partyIdNameMap: map })
  }

  // 选择保全人
  selectBaoQuanRen (e) {
    const c = this.props.formRef.current
    const { partyIdNameMap } = this.state
    const vars = c.getFieldValue(['vars'])
    vars.preservation_partyid = e
    vars.preservation_party = e.map(li => partyIdNameMap[li])
    c.setFieldsValue({ vars })
  }

  // 获取法院列表
  getCourtList () {
    const hide = message.loading('获取法院列表中')
    this.$get('/api/xapc/court')
      .then(res => {
        hide()
        if (res.status === 1) {
          this.setState({
            courtList: res.data
          })
        } else {
          message.warning(res)
        }
      }).catch(() => hide())
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
    }
    if (this.props.caseDetail !== prev.caseDetail) {
      this.initPartyIdNameMap()
    }
  }

  componentDidMount () {
    this.getCourtList()
    this.initKeyTitleMap()
    this.initPartyIdNameMap()
    const d = new Dictionary()
    d.init('文书盖章类型')
      .then(res => {
        this.setState({
          sealTypes: d.getList('文书盖章类型')
        })
      })
      .catch(e => console.error(e))
  }

  render () {
    const { applicants, respondents } = this.props.caseDetail
    const { keyTitleMap } = this.state
    return (
      <div>
        <Line>
          <Cell>
            <Item {...layout} label='发起秘书'>
              <span>{this.props.userInfo.realname}</span>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={['vars', 'preservation_party']} noStyle><span /></Item>
            <Item {...layout} name={['vars', 'preservation_partyid']} label={keyTitleMap.preservation_party} rules={[{ required: true, message: `${keyTitleMap.preservation_party}不能为空` }]}>
              <Select mode='multiple' placeholder={`请选择${keyTitleMap.preservation_party}`} onChange={e => this.selectBaoQuanRen(e)}>
                <OptGroup label='申请人'>
                  {
                    applicants.filter(li => li.status).map(li => (<Option key={li.id} value={li.id}>{li.name}</Option>))
                  }
                </OptGroup>
                <OptGroup label='被申请人'>
                  {
                    respondents.filter(li => li.status).map(li => (<Option key={li.id} value={li.id}>{li.name}</Option>))
                  }
                </OptGroup>
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={['vars', 'preservation_type']} label={keyTitleMap.preservation_type} rules={[{ required: true, message: `${keyTitleMap.preservation_type}不能为空` }]}>
              <Select placeholder={`请选择${keyTitleMap.preservation_party}`}>
                <Option value='财产保全'>财产保全</Option>
                <Option value='证据保全'>证据保全</Option>
              </Select>
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item {...layout} name={['vars', 'preservation_court']} label={keyTitleMap.preservation_court}>
              <Input placeholder={`请输入${keyTitleMap.preservation_court}，多个法院时请用逗号隔开`} />
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item {...layout} name={['vars', 'delay_day']} label={keyTitleMap.delay_day} rules={[{ required: true, message: `${keyTitleMap.delay_day}不能为空` }, { type: 'number', message: '请输入数字' }]}>
              <DelayDay />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item name={['vars', 'preservation_document_sealtype']} label={keyTitleMap.preservation_document_sealtype} rules={[{ required: true, message: `${keyTitleMap.preservation_document_sealtype}不能为空` }]}>
              <Select placeholder='请选择'>
                {this.state.sealTypes.map((li, i) => <Option key={i} value={li.value}>{li.title}</Option>)}
              </Select>
            </Item>
          </Cell>
        </Line>
      </div>
    )
  }
}

SecretaryInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object
}

SecretaryInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(SecretaryInput)

// 暂缓日期输入组件
class DelayDay extends React.Component {
  state = {
    status: false
  }

  setStatus (e) {
    this.setState({
      status: e
    }, () => {
      this.props.onChange(e ? 10 : 0)
    })
  }

  renderInput () {
    if (this.state.status) {
      return (
        <>
          <InputNumber min={1} value={this.props.value} onChange={e => this.props.onChange(e)} className={style['delay-day-input']} placeholder='请输入' />
          <span className={style.unit}>工作日</span>
        </>
      )
    }
  }

  render () {
    return (
      <div className={style['delay-day']}>
        <Select value={this.state.status} className={style['dalay-select']} onChange={e => this.setStatus(e)}>
          <Option value>是</Option>
          <Option value={false}>否</Option>
        </Select>
        {this.renderInput()}
      </div>
    )
  }
}

DelayDay.proptypes = {
  value: PropTypes.number,
  onChange: PropTypes.func
}

DelayDay.defaultProps = {
  value: 0,
  onChange: () => {}
}
